package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.constants.MqConstants;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.mapper.OrderDetailMapper;
import com.xmy.cultivate.mapper.StudentAccountMapper;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.respons.ResStudentAccount;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 帐号 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2024-03-20
 */
@Service
public class StudentAccountServiceImpl extends ServiceImpl<StudentAccountMapper, StudentAccount> implements IStudentAccountService {

    @Autowired
    IStudentService iStudentService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    ICourseService iCourseService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    StudentAccountMapper studentAccountMapper;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    IAdminService iAdminService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    /**
     * 报名添加学员帐号
     *
     * @return
     */
    @Override
    public Result applyAddStudentAccount(OrderDetail orderDetail) {
        try {
            Student student = iStudentService.getById(orderDetail.getStudentId());
            Quarter quarter = iQuarterService.getNowQuarter();

            QueryWrapper<StudentAccount> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("student_id", student.getId());
            accountQueryWrapper.last("limit 1");
            StudentAccount studentAccount = this.getOne(accountQueryWrapper);
            Course course = iCourseService.getById(orderDetail.getCourseId());
            Grade gradeNew = null;
            gradeNew = iGradeService.getById(orderDetail.getGradeId());
            if (gradeNew == null) {
                return new Result(Code.ERROR, "", "更新失败：未分班");
            }
            //不等于英语，或者不等于精品课直接返回
            if (!course.getSubjectsId().equals(1L) || !gradeNew.getLessonType().equals(1)) {
                return new Result(Code.ERROR, "", "更新失败：未分班");
            }

            if (studentAccount == null) {
                studentAccount = new StudentAccount();

                studentAccount.setId(idWorker.nextId());
                studentAccount.setSchoolId(orderDetail.getSchoolId());
                studentAccount.setStudentId(student.getId());
                studentAccount.setStudentName(student.getName());
                studentAccount.setStatus(1);
                studentAccount.setAccountType(1);
                studentAccount.setAddType(1);
                studentAccount.setYearPart(quarter.getYearPart());
                studentAccount.setQuarterNum(quarter.getNum());
                studentAccount.setGradeId(orderDetail.getGradeId());
                //studentAccount.setYearClassId(gradeNew.getYearClassId().getKey());

                if (gradeNew != null) {
                    studentAccount.setClassTypeId(gradeNew.getCourseTypeId());//班型
                    studentAccount.setYearPart(gradeNew.getYearPart());
                }

                studentAccount.setYearClassId(course.getYearClassId().getKey());
                studentAccount.setQuarterNum(course.getQuarterNum());
                String account = this.getAccountStr(orderDetail.getStudentId(), student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
                String pwd = this.getAccountPwd(orderDetail.getStudentId(), student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
                studentAccount.setAccount(account);
                studentAccount.setPwd(pwd);
                this.save(studentAccount);
            } else {
                if (gradeNew != null) {
                    studentAccount.setSchoolId(orderDetail.getSchoolId());
                    studentAccount.setClassTypeId(gradeNew.getCourseTypeId());//班型
                    studentAccount.setGradeId(gradeNew.getId());
                    studentAccount.setYearPart(gradeNew.getYearPart());
                    studentAccount.setQuarterNum(gradeNew.getQuarterNum());
                    studentAccount.setYearClassId(course.getYearClassId().getKey());
                    studentAccount.setGradeId(orderDetail.getGradeId());
                }
                this.updateById(studentAccount);
            }

            try {
                //转为map
                //Map map = BeanMapUtils.beanToMap(studentAccount);
                ResStudentAccount resStudentAccount = new ResStudentAccount();
                BeanUtils.copyProperties(studentAccount, resStudentAccount);
                if (gradeNew != null) {
                    resStudentAccount.setTeacherId(gradeNew.getTeacherId());
                    resStudentAccount.setGradeSection(CommonUtil.getGradeSection(gradeNew.getYearClassId().getKey()));
                }
                //iFeiEnglishFeignClient.addAccount(resStudentAccount);
                //更新班型
                //this.updateClassType(gradeNew.getYearPart(),course.getQuarterNum(),course.getSubjectsId(),studentId);
            } catch (Exception e) {
                return new Result(Code.ERROR, "", "更新失败：" + e.getMessage());
            }
            return new Result(Code.OK, "", "更新成功");
        } catch (Exception e) {
            return new Result(Code.ERROR, "", "更新失败：" + e.getMessage());
        }
    }

    @Override
    public Result addStudentAccountBatch(Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId) {
//        try {
        Integer lessonType = 1;
        Quarter quarter = new Quarter();
        quarter.setYearPart(yearPart);
        quarter.setNum(quarterNum);

        List<StudentGrade> studentGradeList = studentGradeMapper.getReadingData(quarter.getYearPart(), quarter.getNum(), studentId, subjectsId, lessonType);

        Staff staff = iStaffService.getById(studentId);

        if (studentGradeList.isEmpty()) {

            StudentGrade studentGrade = new StudentGrade();
            studentGrade.setStudentId(studentId);
            studentGrade.setYearPart(yearPart);
            studentGrade.setQuarterNum(quarterNum);
            if (staff.getSchoolId() != null) {
                studentGrade.setSchoolId(staff.getSchoolId());
            } else {
                studentGrade.setSchoolId(1891751265138900992L);
            }
            studentGrade.setSubjectsId(subjectsId);

            StudentAccount studentAccount = this.addStudentAccount(studentGrade, null);
            ResStudentAccount resStudentAccount = new ResStudentAccount();
            BeanUtils.copyProperties(studentAccount, resStudentAccount);
            resStudentAccount.setYearPart(yearPart);
            resStudentAccount.setQuarterNum(quarterNum);
            resStudentAccount.setYearClassId(3);
            resStudentAccount.setGradeSection(CommonUtil.getGradeSection(3));
            resStudentAccount.setClassTypeId(1565023758494501025L);
            resStudentAccount.setAccountType(2);
            resStudentAccount.setSubjectsId(studentGrade.getSubjectsId());

            Student student = iStudentService.getById(studentGrade.getStudentId());
            if (student != null) {
                if (student.getLinkman() != null && student.getLinkmanPhone() != null) {
                    resStudentAccount.setLinkman(student.getLinkman());
                    resStudentAccount.setLinkmanPhone(student.getLinkmanPhone());
                }
                resStudentAccount.setStudentName(student.getName());
                String account = this.getAccountStr(studentGrade.getStudentId(), student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
                String pwd = this.getAccountPwd(studentGrade.getStudentId(), student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
                studentAccount.setAccount(account);
                studentAccount.setPwd(pwd);
            }

//                try {


            rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_SYNC_APPLY_STUDENT_ACCOUNT_FANOUT, null, resStudentAccount);
//                } catch (Exception e) {
//                    System.out.println(e.getMessage());
//                }

        } else {
            for (StudentGrade studentGrade : studentGradeList) {
                Grade gradeNew = iGradeService.getById(studentGrade.getGradeId());
                if (gradeNew == null) {
                    System.out.println("班级为空：" + gradeNew.getId());
                    continue;
                }
                Course course = iCourseService.getById(gradeNew.getCourseId());
                StudentAccount studentAccount = this.addStudentAccount(studentGrade, gradeNew);

                ResStudentAccount resStudentAccount = new ResStudentAccount();
                BeanUtils.copyProperties(studentAccount, resStudentAccount);
                resStudentAccount.setGradeId(studentGrade.getGradeId());
                resStudentAccount.setClassTypeId(gradeNew.getCourseTypeId());
                resStudentAccount.setYearClassId(gradeNew.getYearClassId().getKey());
                resStudentAccount.setYearPart(gradeNew.getYearPart());
                resStudentAccount.setQuarterNum(gradeNew.getQuarterNum());
                resStudentAccount.setTeacherId(gradeNew.getTeacherId());
                Staff teacher = iStaffService.getById(gradeNew.getTeacherId());
                if (staff != null) {
                    resStudentAccount.setTeacherName(teacher.getName());
                }
                resStudentAccount.setGradeSection(CommonUtil.getGradeSection(gradeNew.getYearClassId().getKey()));
                resStudentAccount.setSubjectsId(course.getSubjectsId());
                resStudentAccount.setReadingStatus(studentGrade.getReadingStatus().getKey());
                resStudentAccount.setAccountType(2);
                Student student = iStudentService.getById(studentGrade.getStudentId());
                if (student != null) {
                    if (student.getLinkman() != null && student.getLinkmanPhone() != null) {
                        resStudentAccount.setLinkman(student.getLinkman());
                        resStudentAccount.setLinkmanPhone(student.getLinkmanPhone());
                    }
                    String account = this.getAccountStr(studentGrade.getStudentId(), student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
                    String pwd = this.getAccountPwd(studentGrade.getStudentId(), student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
                    studentAccount.setAccount(account);
                    studentAccount.setPwd(pwd);
                }

//                    try {
                rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_SYNC_STUDENT_ACCOUNT_FANOUT, null, resStudentAccount);
//                    } catch (Exception e) {
//                        System.out.println(e.getMessage());
//                    }
            }
        }
//        } catch (Exception e) {
//            return new Result(Code.ERROR, "", "更新失败：" + e.getMessage());
//        }
        return new Result(Code.OK, "", "");
    }

    public StudentAccount addStudentAccount(StudentGrade studentGrade, Grade gradeNew) {
        Staff staff = iStaffService.getById(studentGrade.getStudentId());

        QueryWrapper<StudentAccount> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("student_id", studentGrade.getStudentId());
        accountQueryWrapper.last("limit 1");
        StudentAccount studentAccount = this.getOne(accountQueryWrapper);


        if (studentAccount == null) {
            studentAccount = new StudentAccount();
            studentAccount.setId(idWorker.nextId());

            String account = this.getAccountStr(studentGrade.getStudentId(), staff.getName(), null, staff.getPhone());
            String pwd = this.getAccountPwd(studentGrade.getStudentId(), staff.getName(), null, staff.getPhone());
            studentAccount.setAccount(account);
            studentAccount.setPwd(pwd);
        }

        studentAccount.setYearPart(studentGrade.getYearPart());
        studentAccount.setQuarterNum(studentGrade.getQuarterNum());
        studentAccount.setSchoolId(studentGrade.getSchoolId());
        studentAccount.setStudentId(studentGrade.getStudentId());
        studentAccount.setStudentName(staff.getName());
        studentAccount.setStatus(1);
        studentAccount.setAccountType(1);
        studentAccount.setAddType(1);

        if (gradeNew != null) {
            studentAccount.setGradeId(studentGrade.getGradeId());
            studentAccount.setClassTypeId(gradeNew.getCourseTypeId());//班型
            studentAccount.setYearPart(gradeNew.getYearPart());
            studentAccount.setYearClassId(gradeNew.getYearClassId().getKey());
        }

        this.saveOrUpdate(studentAccount);

        return studentAccount;
    }


    public StudentAccount addStudentAccountForStudent(Long studentId) {
        Quarter quarter = iQuarterService.getNowQuarter();
        Student student = iStudentService.getById(studentId);

        QueryWrapper<StudentAccount> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("student_id", studentId);
        accountQueryWrapper.last("limit 1");
        StudentAccount studentAccount = this.getOne(accountQueryWrapper);

        if (studentAccount == null) {
            studentAccount = new StudentAccount();
            studentAccount.setId(idWorker.nextId());
            //studentAccount.setSchoolId(studentGrade.getSchoolId());
            studentAccount.setStudentId(studentId);
            studentAccount.setStudentName(student.getName());
            studentAccount.setStatus(1);
            studentAccount.setAccountType(1);
            studentAccount.setAddType(1);
            studentAccount.setYearPart(quarter.getYearPart());
            studentAccount.setQuarterNum(quarter.getNum());
            //studentAccount.setGradeId(studentGrade.getGradeId());

            //if (gradeNew != null) {
            //    studentAccount.setClassTypeId(gradeNew.getCourseTypeId());//班型
            //    studentAccount.setYearPart(gradeNew.getYearPart());
            //}

            studentAccount.setYearClassId(student.getYearClassId());
            String account = this.getAccountStr(studentId, student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
            String pwd = this.getAccountPwd(studentId, student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
            studentAccount.setAccount(account);
            studentAccount.setPwd(pwd);
            this.save(studentAccount);
        } else {
            //String account = this.getAccountStr(studentGrade.getStudentId(), student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
            //studentAccount.setAccount(account);
            //studentAccount.setPwd(account);
            if (!studentAccount.getStudentName().trim().equals(student.getName().trim())) {
                String account = this.getAccountStr(studentId, student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
                String pwd = this.getAccountPwd(studentId, student.getName(), student.getIdCardNo(), student.getLinkmanPhone());
                studentAccount.setAccount(account);
                studentAccount.setPwd(pwd);
            }
            studentAccount.setStudentName(student.getName());
            this.updateById(studentAccount);
        }
        return studentAccount;
    }

    @Override
    public void updateStudentAccountPwd(StudentAccount studentAccount) {
        UpdateWrapper<StudentAccount> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("student_id", studentAccount.getStudentId());
        updateWrapper.set("pwd", studentAccount.getPwd());
        updateWrapper.set("account", studentAccount.getAccount());
        this.update(updateWrapper);
    }

    @Override
    public void addStudentAccount(ResStudentAccount resStudentAccount) {
        Student student = iStudentService.getById(resStudentAccount.getStudentId());
        boolean isUpdate = true;
        if (student == null) {
            student = new Student();
            student.setId(resStudentAccount.getStudentId());
            isUpdate = false;
        }

        student.setName(resStudentAccount.getStudentName());
        student.setSchoolId(resStudentAccount.getSchoolId());
        student.setYearClassId(resStudentAccount.getYearClassId());
        student.setLinkman(resStudentAccount.getLinkman());
        student.setLinkmanPhone(resStudentAccount.getLinkmanPhone());

        if (isUpdate) {
            iStudentService.updateById(student);
        } else {
            iStudentService.save(student);
        }

        Admin adminObj = resStudentAccount.getAdminObj();
        if (adminObj != null) {
            Admin admin = iAdminService.getById(resStudentAccount.getStudentId());
            if (admin == null) {
                iAdminService.save(adminObj);
            } else {
                adminObj.setId(admin.getId());
                iAdminService.updateById(adminObj);
            }
        }

    }


    public String getAccountStr(Long studentId, String studentName, String idCardNo, String linkmanPhone) {
        String str = "";
        if (StringUtils.isNotBlank(idCardNo)) {
            if (idCardNo.length() == 18) {
                str = idCardNo.substring(8, 12);
            }
        } else {
            if (StringUtils.isNotBlank(linkmanPhone) && linkmanPhone.length() == 11) {
                str = linkmanPhone.substring(7, 11);
            }
        }
        if (StringUtils.isBlank(str)) {
            Random random = new Random();
            str = String.valueOf(random.nextInt(9999 - 1000 + 1) + 1000);
        }
        String chinese = studentName;  // 要转换的中文字符串
        String pinyin = CommonUtil.chToPinyin(chinese);

        String account = pinyin + str;
        QueryWrapper<StudentAccount> studentAccountQueryWrapper = new QueryWrapper<>();
        studentAccountQueryWrapper.eq("account", account);
        studentAccountQueryWrapper.ne("student_id", studentId);
        Long count = studentAccountMapper.selectCount(studentAccountQueryWrapper);
        if (count > 0) {
            Random random = new Random();
            str = String.valueOf(random.nextInt(9999 - 1000 + 1) + 1000);
            account = pinyin + str;
        }
        account = account.replace("u:", "v");
        return account;
    }

    public String getAccountPwd(Long studentId, String studentName, String idCardNo, String linkmanPhone) {
        String str = "";
        if (StringUtils.isBlank(str)) {
            Random random = new Random();
            str = String.valueOf(random.nextInt(9999 - 1000 + 1) + 1000);
        }
        String chinese = studentName;  // 要转换的中文字符串
        String pinyin = CommonUtil.chToPinyin(chinese);
        String pwd = pinyin + str;
        pwd = pwd.replace("u:", "v");
        return pwd;
    }

}
